from .errors import LogicError
from .http_utils import ErrorResponse


class HandleLogicErrorMiddleware(object):
    """处理 LogicError 异常中间件"""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        response = self.get_response(request)
        # Code to be executed for each request/response after
        # the view is called.
        return response

    def process_exception(self, request, exc):
        """处理异常"""
        if isinstance(exc, LogicError):
            return ErrorResponse(err_code=exc.code, errmsg=exc.message)
